﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace JQ50037.Procdure
{
    [XmlRoot("系统配置")]
    [Serializable]
    public class Config
    {
        private static string file = "config.xml";

        //[XmlElement("液位报警阈值上限")]
        //public double LiquidLevelMax { get; set; }

        [XmlElement("液位报警阈值下限")]
        public double LiquidLevelMin { get; set; }

        [XmlElement("温度报警阈值上限")]
        public double TemperatureMax { get; set; }

        [XmlElement("温度报警阈值下限")]
        public double TemperatureMin { get; set; }

        [XmlElement("流量报警阈值上限")]
        public double FlowRateMax { get; set; }

        [XmlElement("流量报警阈值下限")]
        public double FlowRateMin { get; set; }

        [XmlElement("仪表端口")]
        public string DevicePort { get; set; }

        [XmlElement]
        public int Hours { get; set; }

        [XmlElement]
        public int Minutes { get; set; }

        [XmlElement]
        public int GoalTemp { get; set; }

        public static Config Load()
        {
            if (!File.Exists(file))
            {
                Config config = new Config
                {
                    DevicePort = "COM1",
                    FlowRateMax = 0,
                    FlowRateMin = 0,
                    TemperatureMax = 0,
                    TemperatureMin = 0,
                    LiquidLevelMin = 0,
                    Hours = 4,
                    Minutes = 0,
                    GoalTemp = 80,
                };
                Save(config);
                return config;
            }
            else
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Config));

                TextReader reader = new StreamReader(file);
                // 初始化默认值

                var obj = serializer.Deserialize(reader);
                reader.Close();
                return obj as Config;
            }
        }

        public static void Save(Config config)
        {
            if (config is null)
            {
                throw new ArgumentNullException("参数错误");
            }
            XmlSerializer serializer = new XmlSerializer(typeof(Config));
            TextWriter writer = new StreamWriter(file);
            serializer.Serialize(writer, config);
            writer.Close();
        }
    }
}